package com.azkj.album.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.RectF;
import android.graphics.Region;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

import com.azkj.album.network.utils.LogUtils;
import com.azkj.album.utils.Utils;

import java.io.InputStream;

public class DraggableCombinedImageView extends View {

    private final Paint paint;
    private final Bitmap[] bitmaps = new Bitmap[3]; // 最多支持三张图片
    private final Matrix[] matrices = new Matrix[3]; // 每张图片对应一个矩阵
    private final Path[] clipPaths = new Path[3]; // 每张图片对应一个裁剪路径
    private int imageViewWidth, imageViewHeight;
    private float lastX, lastY;
    private int draggingIndex = -1; // -1 表示没有图片被拖动
    private final ScaleGestureDetector scaleDetector;
    private float scaleFactor = 1.0f;
    private boolean isScaling = false; // 添加一个标志位来判断是否正在进行缩放操作
    private boolean shouldClearCanvas = false;

    public DraggableCombinedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        setBackgroundColor(Color.TRANSPARENT);

        scaleDetector = new ScaleGestureDetector(context, new ScaleListener()); // 使用自定义的ScaleListener

    }

    public void setImages(String[] imageResIds, int imageViewWidth, int imageViewHeight) {
        this.imageViewWidth = imageViewWidth;
        this.imageViewHeight = imageViewHeight;

        for (int i = 0; i < imageResIds.length; i++) {
            final int index = i;
            matrices[index] = new Matrix();
            clipPaths[index] = createClipPathForIndex(index, imageResIds.length);

            String path = imageResIds[index];
            if (isLocalPath(path)) {
                // 本地图片，直接加载
                bitmaps[index] = scaleToFitWidthOrHeight(Utils.getBitmap(path), imageViewWidth, imageViewHeight);
                invalidate();
            } else {
                // 网络图片，异步加载
                loadBitmapFromURL(path, bitmap -> {
                    bitmaps[index] = scaleToFitWidthOrHeight(bitmap, imageViewWidth, imageViewHeight);
                    invalidate();
                });
            }
        }
    }

    public boolean isLocalPath(String path) {
        return !(path.startsWith("http://") || path.startsWith("https://"));
    }

    private void loadBitmapFromURL(String url, BitmapLoadCallback callback) {
        new AsyncTask<String, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(String... urls) {
                try {
                    InputStream in = new java.net.URL(urls[0]).openStream();
                    return BitmapFactory.decodeStream(in);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                if (result != null && callback != null) {
                    callback.onBitmapLoaded(result);
                }
            }
        }.execute(url);
    }

    public interface BitmapLoadCallback {
        void onBitmapLoaded(Bitmap bitmap);
    }

    private Path createClipPathForIndex(int index, int total) {
        Path path = new Path();
        if (total == 2) {
            // 两张图片时的裁剪路径
            if (index == 0) {
                // 第一张图片的裁剪路径
                // 对角线裁剪路径（从左上角开始，斜切至右侧底部）
                path.moveTo(0, 0); // 左上角
                path.lineTo(imageViewWidth * 0.2f, 0); // 中点上方
                path.lineTo(imageViewWidth * 0.7f, imageViewHeight); // 右下角
                path.lineTo(0, imageViewHeight); // 左下角
                path.close();
            } else {
                // 第二张图片的裁剪路径
                path.moveTo(imageViewWidth * 0.22f, 0); // 左上角
                path.lineTo(imageViewWidth, 0); // 右上角
                path.lineTo(imageViewWidth, imageViewHeight); // 中点上方
                path.lineTo(imageViewWidth * 0.72f, imageViewHeight); // 右下角
                path.close();
            }
        } else if (total == 3) {
            // 三张图片时的裁剪路径
            if (index == 0) {
                // 第一张图片的裁剪路径
                path.moveTo(0, 0); // 左上角开始
                path.lineTo(imageViewWidth, 0);
                path.lineTo(imageViewWidth, imageViewHeight * 0.35f); // 向下斜向中间
                path.lineTo(0, imageViewHeight * 0.75f); // 竖向下半点
                path.close();
            } else if (index == 1) {
                // 第二张图片的裁剪路径
                path.moveTo(0, imageViewHeight * 0.76f); // 顶部中间开始
                path.lineTo(imageViewWidth * 0.54f, imageViewHeight * 0.545f); // 顶部向右至右上角
                path.lineTo(imageViewWidth * 0.7f, imageViewHeight); // 向下至右中角
                path.lineTo(0, imageViewHeight); // 斜向下至第一张图片的分界处
                path.close();
            } else {
                // 第三张图片的裁剪路径
                path.moveTo(imageViewWidth * 0.55f, imageViewHeight * 0.54f); // 左侧下半点开始
                path.lineTo(imageViewWidth, imageViewHeight * 0.36f); // 斜向上至第一张图片的分界处
                path.lineTo(imageViewWidth, imageViewHeight); // 横向至右中角
                path.lineTo(imageViewWidth * 0.71f, imageViewHeight); // 向下至右下角
                path.close();
            }

        } else if (total == 1) {
            // 一张图片时的裁剪路径
            path.addRect(new RectF(0, 0, imageViewWidth, imageViewHeight), Path.Direction.CW);
        }
        return path;
    }

    private Bitmap scaleToFitWidthOrHeight(Bitmap originalBitmap, int viewWidth, int viewHeight) {
        float originalWidth = originalBitmap.getWidth();
        float originalHeight = originalBitmap.getHeight();

        // 计算宽度和高度的缩放因子
        float scaleFactorWidth = viewWidth / originalWidth;
        float scaleFactorHeight = viewHeight / originalHeight;

        // 选择一个较大的缩放因子，以保证至少有一边与视图对齐
        float scaleFactor = Math.max(scaleFactorWidth, scaleFactorHeight);

        // 应用缩放因子
        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(scaleFactor, scaleFactor);

        // 使用缩放矩阵创建一个新的位图
        Bitmap scaledBitmap = Bitmap.createBitmap(
                originalBitmap, 0, 0,
                (int) originalWidth, (int) originalHeight,
                scaleMatrix, true
        );

        return scaledBitmap;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 先清除画布
        if (shouldClearCanvas) {
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.SRC_OVER);

            shouldClearCanvas = false;
        }

        // 绘制每张图片
        for (int i = 0; i < bitmaps.length; i++) {
            if (bitmaps[i] != null && clipPaths[i] != null) {
                canvas.save();

                // 为当前的裁剪区域应用圆角路径
                Path tempClipPath = new Path();
                tempClipPath.addRoundRect(new RectF(0, 0, imageViewWidth, imageViewHeight), 20.0f, 20.0f, Path.Direction.CW);
                tempClipPath.op(clipPaths[i], Path.Op.INTERSECT);

                // 应用裁剪路径
                canvas.clipPath(tempClipPath);

                // 绘制位图
                canvas.drawBitmap(bitmaps[i], matrices[i], paint);

                canvas.restore();
            }
        }
    }

    /**
     * 清空画布
     *
     */
    public void clearCanvas() {
        for (int i = 0; i < bitmaps.length; i++) {
            if (bitmaps[i] != null) {
                bitmaps[i].recycle();
                bitmaps[i] = null;
            }
        }

        shouldClearCanvas = true;
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

//        Log.d("Draggable", "onTouchEvent: " + event.getAction()
//        + "isScaling: " + isScaling + " draggingIndex: " + draggingIndex
//        + "event.getPointerCount(): " + event.getPointerCount());
        // 将事件首先传递给 ScaleGestureDetector
        scaleDetector.onTouchEvent(event);

        // 根据触摸点的数量来区分是拖动还是缩放
        if (event.getPointerCount() == 1 && !isScaling) {
            // 单指触控逻辑 (拖动)
            handleDragEvent(event);
        }
        return true;
    }

    private void handleDragEvent(MotionEvent event) {
        // 打印view实例
        Log.d("Draggable", "View: " + this);
        float x = event.getX();
        float y = event.getY();
        int action = event.getAction();

        switch (action) {
            case MotionEvent.ACTION_DOWN:
//                Log.d("Draggable", "ACTION_DOWN: " + x + ", " + y);
                // 当开始触摸时，告诉父视图不要拦截触摸事件
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                // 检查每张图片，看触摸点是否在其边界内
                for (int i = 0; i < bitmaps.length; i++) {
                    if (isInBitmap(bitmaps[i], x, y, matrices[i], clipPaths[i])) {
                        draggingIndex = i;
                        lastX = x;
                        lastY = y;
//                        Log.d("Draggable", "Dragging image at index: " + draggingIndex);
                        break;
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                // 如果有图片被选中，则对其应用变换
                if (draggingIndex != -1) {
                    // 确保移动的是有效的图片
                    if (matrices[draggingIndex] != null) {
                        matrices[draggingIndex].postTranslate(x - lastX, y - lastY);
                        lastX = x;
                        lastY = y;
                        invalidate();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                // 当触摸结束时，允许父视图再次拦截触摸事件
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                if (draggingIndex != -1 && matrices[draggingIndex] != null) {
                    checkBoundsAndBounceBack(bitmaps[draggingIndex], matrices[draggingIndex]);
                    draggingIndex = -1; // 重置拖动索引
                }
                break;
        }
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            isScaling = true; // 开始缩放时设置标志位
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
//            Log.d("Draggable", "ScaleFactor: " + detector.getScaleFactor());

            scaleFactor *= detector.getScaleFactor();
            scaleFactor = Math.max(0.1f, Math.min(scaleFactor, 5.0f));

            if (draggingIndex != -1 && matrices[draggingIndex] != null) {
                // Debug: 输出当前的缩放级别
//                Log.d("Draggable", "Scaling image at index: " + draggingIndex + " to: " + scaleFactor);

                matrices[draggingIndex].postScale(detector.getScaleFactor(), detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY());
                invalidate();
            }
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            isScaling = false; // 缩放结束时重置标志位
        }
    }

    private void checkBoundsAndBounceBack(Bitmap bitmap, Matrix matrix) {
        if (bitmap == null) return;

        float[] values = new float[9];
        matrix.getValues(values);
        float transX = values[Matrix.MTRANS_X];
        float transY = values[Matrix.MTRANS_Y];
        float bitmapWidth = values[Matrix.MSCALE_X] * bitmap.getWidth();
        float bitmapHeight = values[Matrix.MSCALE_Y] * bitmap.getHeight();

        // 计算图片边界
        float right = transX + bitmapWidth;
        float bottom = transY + bitmapHeight;

        // 检查图片是否有一部分仍在视图区域内
        boolean outOfBounds = right < 0 || bottom < 0 || transX > imageViewWidth || transY > imageViewHeight;

        if (outOfBounds) {
            // 重置Matrix到初始位置
            matrix.reset();
            invalidate();
        }
    }

    private boolean isInBitmap(Bitmap bitmap, float x, float y, Matrix matrix, Path originalClipPath) {
        if (bitmap == null || matrix == null || originalClipPath == null) {
            return false;
        }

        // 将点转换到图片坐标系统中
        Matrix inverse = new Matrix();
        matrix.invert(inverse);
        float[] touchPoint = new float[]{x, y};
        inverse.mapPoints(touchPoint);

        // 检查转换后的点是否在原始的位图边界内
        boolean withinBitmap = touchPoint[0] >= 0 && touchPoint[0] < bitmap.getWidth() &&
                touchPoint[1] >= 0 && touchPoint[1] < bitmap.getHeight();

        if (!withinBitmap) {
            return false;
        }

        return true;

//        // 应用相同的矩阵变换到裁剪路径
//        Path transformedPath = new Path(originalClipPath);
//        transformedPath.transform(matrix);
//
//        // 使用变换后的路径来创建区域并检查点是否在路径内
//        Region region = new Region();
//        Region clip = new Region(0, 0, bitmap.getWidth(), bitmap.getHeight());
//        region.setPath(transformedPath, clip);
//        boolean isInBitmap = region.contains((int) touchPoint[0], (int) touchPoint[1]);
//        Log.d("Draggable", "touchPoint: " + touchPoint[0] + ", " + touchPoint[1] + " isInBitmap: " + isInBitmap);
//
//        Log.d("Draggable", "Bitmap size: " + bitmap.getWidth() + ", " + bitmap.getHeight());
//        Log.d("Draggable", "Transformed touchPoint: " + touchPoint[0] + ", " + touchPoint[1]);
//        Log.d("Draggable", "Matrix: " + matrix);
//        Log.d("Draggable", "ClipPath: " + originalClipPath);
//        return isInBitmap;
    }


}
